#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "seqlist.h"

static void show_char(const void *data);

static void show_str(const void *data);

static void show_int(const void *data);

static int char_cmp(const void *data, const void *key);

static int int_cmp(const void *data, const void *key);

static int string_cmp(const void *data, const void *key);

int main(int argc, char *argv[])
{
	int i;
	char *del;
	int arr[12];

	seq_t *c_list = NULL;
	seq_t *int_list = NULL;
	seq_t *str_list = NULL;

	if (argc < 2) {
		return 1;
	}

	srand(time(NULL));

	seqlist_init(&c_list, strlen(argv[1]), sizeof (char));
	seqlist_init(&int_list, 12, sizeof (int));
	seqlist_init(&str_list, argc, sizeof (char *));

	for (i = 0; argv[1][i]; i++) {
		//seqlist_insert(c_list, argv[1] + i);
		seqlist_insert_sort(c_list, argv[1] + i, char_cmp);
	}

	seqlist_travel(c_list, show_char);
	printf("\n");

	for (i = 0; i < argc; i++) {
		// argv + i    是一个指向字符串首地址的指针的地址
		// *(argv + i) 是字符串首地址
		// %s输出字符串首地址 打印字符串内容
		// %p输出字符串首地址 打印该地址
		//printf("Inserting %p %s (string stored at %p)\n", argv + i, *(argv + i), *(argv + i));
		// 把指向这些字符串的指针复制一份存进数组，但不复制字符串本身
		seqlist_insert_tail(str_list, argv + i);
	}

	seqlist_travel(str_list, show_str);
	printf("\n");

	for (i = 0; i < 12; i++) {
		arr[i] = rand() % 100;
		show_int(&arr[i]);
		seqlist_insert_sort(int_list, &(arr[i]), int_cmp);
	}
	printf("\n");

	seqlist_travel(int_list, show_int);
	printf("\n");

	del = "hello";

	if (-1 == seqlist_delete(str_list, &del, string_cmp)) {
		printf("Not found\n");
	} else {
		printf("Deleted\n");
	}

	seqlist_travel(str_list, show_str);
	printf("\n");

	seqlist_destroy(&c_list);
	seqlist_destroy(&int_list);
	seqlist_destroy(&str_list);

	return 0;
}

static void show_char(const void *data)
{
	char *d = (char *) data;
	printf("%c ", *d);
}

static void show_int(const void *data)
{
	int *d = (int *) data;
	printf("%d ", *d);
}

static void show_str(const void *data)
{
	char **d = (char **) data;
	
	char *str = *d;
	printf("%s ", str);
	
	//printf("[%p]: %s\n", d, *d);
}

static int char_cmp(const void *data, const void *key)
{
	return *((char *) data) - *((char *) key);
}

static int int_cmp(const void *data, const void *key)
{
	return *((int *) data) - *((int *) key);
}

static int string_cmp(const void *data, const void *key)
{
	int res;

	char **a = (char **) data;
	char **b = (char **) key;

	return strcmp(*a, *b);
}
